// eslint-disable-next-line @typescript-eslint/no-var-requires
const fs = require('fs');
// eslint-disable-next-line @typescript-eslint/no-var-requires
const path = require('path');
// eslint-disable-next-line @typescript-eslint/no-var-requires
const webpack = require('webpack');
// const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const CopyPlugin = require('copy-webpack-plugin');

const baseUrl = path.join(__dirname, '../src');

module.exports = {
    node: {
        fs: 'empty',
    },
    entry: fs.readdirSync(baseUrl).reduce((entries, dir) => {
        const fullDir = path.join(baseUrl, dir);
        const entry = path.join(fullDir, 'index.ts');
        if (fs.statSync(fullDir).isDirectory() && fs.existsSync(entry)) {
            entries[dir] = [entry];
        }
        return entries;
    }, {}),

    output: {
        path: path.join(__dirname, '../dist/__build__'),
        filename: '[name].js',
        chunkFilename: '[id].chunk.js',
        publicPath: '__build__/',
    },

    module: {
        rules: [
            {
                test: /\.drcwasm$/,
                loaders: ['arraybuffer-loader'],
            },
            {
                test: [/\.svg$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
                use: [
                    {
                        loader: 'file-loader',
                    },
                ],
            },
            { test: /\.js$/, exclude: /node_modules/, use: ['cache-loader', 'babel-loader'] },
            { test: /\.css$/, use: ['cache-loader', 'style-loader', 'css-loader'] },
            {
                test: /\.less$/,
                use: ['cache-loader', 'style-loader', 'css-loader', 'less-loader'],
            },
            { test: /\.tsx?$/, exclude: /node_modules/, use: ['cache-loader', 'ts-loader'] },
        ],
    },

    resolve: {
        alias: {
            '@qunhe/custom-ksg-viewer-api': '@qunhe/custom-ksg-viewer-api/src/vm-api',
        },
        extensions: ['.js', '.ts', '.d.ts', '.tsx', '.css'],
    },

    optimization: {
        // splitChunks: {
        //     cacheGroups: {
        //         vendors: {
        //             name: 'shared',
        //             filename: 'shared.js',
        //             chunks: 'initial',
        //         },
        //     },
        // },
    },

    plugins: [
        new webpack.DefinePlugin({
            VERSION: '',
            CONFIG: {
                DEPLOY_VERSION: '1.0',
                APP_VERSION: '1.0',
            },
            Ktracker: {
                sendErrorV2() {},
            },
        }),
        new CopyPlugin({
            patterns: [
                { from: path.join(__dirname, '../public'), to: path.join(__dirname, '../dist') },
            ],
        }),
        // new BundleAnalyzerPlugin()
    ],
};

